package org.dromara.quickswing.updater;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.List;

public class AutoUpdater {

    private final String downloadUrl;

    private final UpdateChecker updateChecker;

    public AutoUpdater(String downloadUrl, UpdateChecker updateChecker) {
        this.downloadUrl = downloadUrl;
        this.updateChecker = updateChecker;
    }

    public void checkNewVersion(String currentVersion) throws IOException {
        boolean update = updateChecker.checkForUpdate(currentVersion);
        if (update) {
            downloadLatestVersion();
            installLatestVersion();
        }
    }

    private void downloadLatestVersion() {
        try {
            URL url = new URL(downloadUrl);
            ReadableByteChannel rbc = Channels.newChannel(url.openStream());
            FileOutputStream fos = new FileOutputStream("latest_version.jar");
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();
            rbc.close();

        } catch (IOException ignored) {

        }
    }

    private void installLatestVersion() throws IOException {
        List<String> command = new ArrayList<>();
        command.add("java");
        command.add("-jar");
        command.add("latest_version.jar");

        ProcessBuilder processBuilder = new ProcessBuilder(command);

        processBuilder.directory(new File("path/to/directory"));

        Process process = processBuilder.start();

        try {
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                restartApplication();
            } else {

            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    private void restartApplication() {
        String javaCommand = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
        String classpath = System.getProperty("java.class.path");
        String className = AutoUpdater.class.getName();

        List<String> command = new ArrayList<>();
        command.add(javaCommand);
        command.add("-cp");
        command.add(classpath);
        command.add(className);

        ProcessBuilder processBuilder = new ProcessBuilder(command);

        try {
            processBuilder.start();
        } catch (IOException ignored) {

        }

        System.exit(0);
    }
}
